import {
  ProFormDatePicker,
  ProFormInstance,
  ProFormSelect,
  ProFormTreeSelect,
  QueryFilter,
} from '@/components/Pro/';
import { getFilterList, parseArray } from '@/pages/Statistics/Battery/utils';
import { statisticCurrentControllerGetSocData } from '@/services/ess/statisticBatteryCurrent';
import { statisticSocControllerGetSocData } from '@/services/ess/statisticBatterySoc';
import { statisticVoltageControllerGetSocData } from '@/services/ess/statisticBatteryVoltage';
import { useIntl, useModel } from '@umijs/max';
import type { DatePickerProps } from 'antd';
import { message, Spin } from 'antd';
import ReactEcharts from 'echarts-for-react';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';

const TableList: React.FC<{
  type: number;
  deviceInfo: API.DeviceInfo[];
}> = ({ type, deviceInfo }) => {
  const { initialState } = useModel('@@initialState');
  const intl = useIntl();
  const chartRef = useRef();
  const formRef = useRef<ProFormInstance>();
  const [pageData, setPageData] = useState({});
  const [loading, setLoading] = useState(false);
  const [isEmpty, setEmpty] = useState(true);

  useEffect(() => {
    chartRef?.current?.getEchartsInstance()?.resize();
  });

  useEffect(() => {
    if (deviceInfo?.length) {
      formRef?.current?.setFieldsValue({
        codes:
          type === 1
            ? deviceInfo[0]?.code
            : initialState?.isArea
            ? deviceInfo[0].children[0]?.code
            : deviceInfo[0]?.code,
      });
      formRef?.current?.submit();
    }
  }, [type, deviceInfo]);

  const disabledDate: DatePickerProps['disabledDate'] = (current) => {
    const disabled = current && current >= moment().endOf('day');
    return disabled;
  };

  return (
    <div>
      <QueryFilter
        split
        formRef={formRef}
        onFinish={async (value) => {
          if (!value?.codes || !value?.codes?.length) {
            message.warning(intl.formatMessage({ id: 'statistics.analyze.objWarning' }));
            return;
          }
          if (value?.codes?.length > 100) {
            message.warning(intl.formatMessage({ id: 'statistics.analyze.objWarning100' }));
            return;
          }
          value.codes = value.codes ?? [];
          setLoading(true);
          let getData;
          const ans = parseArray(value.codes, true);
          const filterList = getFilterList(ans);
          if (type === 1) {
            if (ans.nodeType.length) {
              let hasAreaNode: boolean = false;
              hasAreaNode = ans.nodeType.some((item: string) => {
                return item === 'AREA';
              });
              if (hasAreaNode) {
                value.areaIdList = filterList.areaList;
                value.codes = filterList.codeList;
              } else {
                value.codes = filterList.codeList;
                value.areaIdList = null;
              }
            }
            getData = statisticSocControllerGetSocData;
          } else if (type === 2) {
            console.log('values.code0', filterList);
            value.codes = filterList.codeList.length ? filterList.codeList : filterList.areaList;
            getData = statisticVoltageControllerGetSocData;
          } else if (type === 3) {
            value.codes = filterList.codeList.length ? filterList.codeList : filterList.areaList;
            getData = statisticCurrentControllerGetSocData;
          }
          try {
            const res = await getData(value);
            setLoading(false);
            if (res?.success) {
              const data = res?.data;
              chartRef?.current?.getEchartsInstance()?.clear();
              setEmpty(!data?.xaxis?.length || !data?.yaxis?.length);
              setPageData({
                xData: data?.xaxis ?? [],
                yData: data?.yaxis ?? [],
              });
            } else {
              chartRef?.current?.getEchartsInstance()?.clear();
            }
          } catch (e) {
            setLoading(false);
            setPageData({
              xData: [],
              yData: [],
            });
            chartRef?.current?.getEchartsInstance()?.clear();
          }
        }}
        onReset={() => {
          formRef?.current?.setFieldsValue({
            codes:
              type === 1
                ? deviceInfo[0]?.code
                : initialState?.isArea
                ? deviceInfo[0].children[0]?.code
                : deviceInfo[0]?.code,
          });
          formRef?.current?.submit();
        }}
      >
        <ProFormDatePicker
          name="startDate"
          label={intl.formatMessage({ id: 'statistics.income.select' })}
          initialValue={moment()}
          fieldProps={{
            disabledDate: disabledDate,
            allowClear: false,
          }}
        />
        <ProFormTreeSelect
          name="codes"
          label={intl.formatMessage({ id: 'statistics.curve.selObject' })}
          initialValue={deviceInfo[0]?.code}
          fieldProps={{
            treeData: deviceInfo,
            fieldNames: {
              label: 'name',
              value: 'code',
              children: 'children',
            },
            multiple: true,
            maxTagCount: 'responsive',
            showSearch: true,
            treeNodeFilterProp: 'name',
            maxCount: 100,
          }}
        ></ProFormTreeSelect>
        <ProFormSelect
          label={intl.formatMessage({ id: 'statistics.curve.interval' })}
          name="interval"
          initialValue={30}
          options={[
            {
              label: `30${intl.formatMessage({ id: 'global.secondUnit' })}`,
              value: 30,
            },
            {
              label: `1${intl.formatMessage({ id: 'global.minuteUnit' })}`,
              value: 60,
            },
            {
              label: `2${intl.formatMessage({ id: 'global.minuteUnit' })}`,
              value: 60 * 2,
            },
            {
              label: `5${intl.formatMessage({ id: 'global.minuteUnit' })}`,
              value: 60 * 5,
            },
            {
              label: `10${intl.formatMessage({ id: 'global.minuteUnit' })}`,
              value: 60 * 10,
            },
            {
              label: `30${intl.formatMessage({ id: 'global.minuteUnit' })}`,
              value: 60 * 30,
            },
            {
              label: `1${intl.formatMessage({ id: 'global.hourUnit' })}`,
              value: 60 * 60,
            },
          ]}
          allowClear={false}
        ></ProFormSelect>
      </QueryFilter>
      <Spin spinning={loading}>
        <ReactEcharts
          ref={chartRef}
          style={{ height: 400, marginTop: 0 }}
          option={{
            tooltip: {
              trigger: 'axis',
              confine: true,
              // axisPointer: {
              //   type: 'shadow',
              // },
              formatter: function (params) {
                const unit = (type === 2 && 'V') || (type === 3 && 'A') || '%';
                let text = `<div>${params[0].axisValueLabel}<br/>`;
                (params || []).forEach((item, index) => {
                  text += `${item.marker}${item.seriesName}&nbsp;:&nbsp;
                  ${item.value ?? ''}${
                    item.value !== undefined && item.value !== null ? unit : ''
                  }&nbsp;&nbsp;&nbsp;&nbsp;`;
                  if ((params || [])?.length < 10) {
                    text += '<br/>';
                  } else {
                    let wrapLen = 3;
                    if ((params || [])?.length > 50) {
                      wrapLen = 4;
                    }
                    if ((index + 1) % wrapLen === 0) {
                      text += '<br/>';
                    }
                  }
                });
                text += '</div>';
                return text;
              },
            },
            legend: {
              type: 'scroll',
              orient: 'horizontal',
              top: 5,
              right: 0,
              //icon: 'item',
            },
            grid: {
              left: 25,
              right: 5,
              top: 60,
              bottom: 15,
              containLabel: true,
              show: true,
              borderColor: 'transparent',
              backgroundColor: isEmpty ? 'transparent' : '#F8F9FA',
            },
            dataZoom: {
              type: 'inside',
            },
            xAxis: [
              {
                type: 'category',
                nameTextStyle: {
                  //y轴上方单位的颜色
                  color: '#222',
                },
                data: pageData?.xData || [],
                axisTick: {
                  alignWithLabel: true,
                  show: true,
                  inside: true, //刻度内置
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#ddd',
                  },
                },
                axisLabel: {
                  color: '#222',
                  formatter: function (value) {
                    const formatVal = value?.substring(11)?.substring(0, 5);
                    // if(formatVal === '00'){
                    //   return ""
                    // }
                    return formatVal;
                  },
                },
              },
            ],
            yAxis: [
              {
                type: 'value',
                name: `${intl.formatMessage({ id: 'bigdata.unitS' })}${
                  (type === 2 && 'V') || (type === 3 && 'A') || '%'
                }`,
                nameTextStyle: {
                  //y轴上方单位的颜色
                  color: '#222',
                  align: 'left',
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: '#ddd',
                  },
                },
                axisTick: {
                  show: true,
                  inside: true,
                },
                splitLine: {
                  show: !isEmpty,
                  lineStyle: {
                    type: 'dashed',
                  },
                },
                axisLabel: {
                  color: '#222',
                },
              },
            ],
            series: (pageData?.yData || []).map((item) => {
              return {
                name: item.title,
                type: 'line',
                data: item.pointsValues?.length ? [...item.pointsValues] : [],
                smooth: true,
                symbol: 'none',
              };
            }),
            graphic: [
              {
                type: 'image',
                silent: true,
                style: {
                  image: require('@/assets/img/empty.png'),
                  width: 180,
                  height: 120,
                },
                bounding: 'raw',
                top: 'center',
                left: 'center',
                invisible: !isEmpty,
              },
              {
                type: 'text', // 类型：文本
                left: 'center',
                top: 280,
                silent: true, // 不响应事件
                invisible: !isEmpty, // 有数据就隐藏
                style: {
                  fill: '#222',
                  text: intl.formatMessage({ id: 'global.noDataYet' }),
                  fontFamily: 'Microsoft YaHei',
                  fontSize: '14px',
                },
              },
            ],
          }}
        />
      </Spin>
    </div>
  );
};
export default TableList;
